package app.ep1.bandejoes;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import app.ep1.R;

public class InformacoesBandejaoActivity extends Activity {
	private String nomeBandejao = null;

	private List<OpiniaoBandejao> listaDeOpinioes = new ArrayList<OpiniaoBandejao>();
	private int indiceDoComentarioAtual;

	private Button buttonAnterior;
	private Button buttonProximo;

	private static int REQUEST_CODE = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.informacoes_bandejao);

		try {
			Bundle bundle = this.getIntent().getExtras();
			this.nomeBandejao = bundle.getString("nomeBandejao");

			TextView textView = (TextView) findViewById(R.id.textViewNomeBandejao);
			textView.setText(nomeBandejao);
		} catch (Exception e) {
		}

		buttonAnterior = (Button) findViewById(R.id.buttonAnteriorComentarioBandejao);
		buttonAnterior.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				carregaComentarioNaTela(indiceDoComentarioAtual - 1);
			}
		});

		buttonProximo = (Button) findViewById(R.id.buttonProximoComentarioBandejao);
		buttonProximo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				carregaComentarioNaTela(indiceDoComentarioAtual + 1);
			}
		});

		Button enviarComentario = (Button) findViewById(R.id.buttonEnviarComentarioBandejao);
		enviarComentario.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString("nomeBandejao",
						transformaNomeBandejaoParaEnvio(nomeBandejao));

				Intent i = new Intent(v.getContext(),
						EnviaInformacoesBandejaoActivity.class);
				i.putExtras(bundle);
				startActivityForResult(i, REQUEST_CODE);
			}
		});

		carregaComentariosEColocaNaTela();
	}

	private void carregaComentariosEColocaNaTela() {
		if (nomeBandejao == null)
			return;

		JSONObject json = getInformacaoDoBandejao(transformaNomeBandejaoParaEnvio(nomeBandejao));

		try {
			JSONArray jsonArray = json.getJSONArray("list");

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);

				OpiniaoBandejao opiniaoBandejao = new OpiniaoBandejao(
						jsonObject);

				listaDeOpinioes.add(opiniaoBandejao);
			}

			Collections.reverse(listaDeOpinioes);
		} catch (Exception e) {
			e.printStackTrace();
		}

		carregaComentarioNaTela(0);
	}

	private JSONObject getInformacaoDoBandejao(String nome) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(
				"http://valinhos.ime.usp.br:56080/usp-mobile/bandejao/" + nome);

		HttpResponse httpResponse;
		JSONObject jsonObject = null;

		try {
			httpResponse = httpClient.execute(httpGet);

			HttpEntity httpEntity = httpResponse.getEntity();

			if (httpEntity != null) {
				InputStream inputStream = httpEntity.getContent();
				String result = streamToString(inputStream);

				jsonObject = new JSONObject(result);

				inputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return jsonObject;
	}

	private static String streamToString(InputStream inputStream) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		StringBuilder stringBuilder = new StringBuilder();

		String line = null;

		try {
			while ((line = reader.readLine()) != null)
				stringBuilder.append(line + "\n");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return stringBuilder.toString();
	}

	private String transformaNomeBandejaoParaEnvio(String string) {
		string = string.toLowerCase();
		string = string.replaceAll(" ", "_");

		string = string.replaceAll("[ÂÀÁÄÃ]", "A");
		string = string.replaceAll("[âãàáä]", "a");
		string = string.replaceAll("[ÊÈÉË]", "E");
		string = string.replaceAll("[êèéë]", "e");
		string = string.replaceAll("ÎÍÌÏ", "I");
		string = string.replaceAll("îíìï", "i");
		string = string.replaceAll("[ÔÕÒÓÖ]", "O");
		string = string.replaceAll("[ôõòóö]", "o");
		string = string.replaceAll("[ÛÙÚÜ]", "U");
		string = string.replaceAll("[ûúùü]", "u");
		string = string.replaceAll("Ç", "C");
		string = string.replaceAll("ç", "c");
		string = string.replaceAll("[ýÿ]", "y");
		string = string.replaceAll("Ý", "Y");
		string = string.replaceAll("ñ", "n");
		string = string.replaceAll("Ñ", "N");
		string = string.replaceAll("['<>\\|/]", "");

		return string;
	}

	public void carregaComentarioNaTela(int indice) {
		if (indice < 0 || indice >= listaDeOpinioes.size())
			return;

		OpiniaoBandejao opiniaoBandejao = listaDeOpinioes.get(indice);

		TextView data = (TextView) findViewById(R.id.textViewDataComentarioBandejao);
		data.setText(opiniaoBandejao.getData().toString());

		ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBarComentarioBandejao);
		progressBar.setProgress(opiniaoBandejao.getFila().getValor() * 20);

		TextView comentario = (TextView) findViewById(R.id.textViewComentarioBandejao);
		comentario.setText(opiniaoBandejao.getTexto());

		buttonAnterior.setEnabled(true);
		buttonProximo.setEnabled(true);

		if (indice == 0)
			buttonAnterior.setEnabled(false);

		if (indice == listaDeOpinioes.size() - 1)
			buttonProximo.setEnabled(false);

		indiceDoComentarioAtual = indice;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode != REQUEST_CODE)
			return;

		if (resultCode != RESULT_OK)
			return;

		carregaComentariosEColocaNaTela();
	}

	public void setListaDeOpinioes(List<OpiniaoBandejao> opinioes) {
		listaDeOpinioes = opinioes;
	}
}